package net.zjitc.boot_demo.controller;


import jakarta.servlet.http.HttpServletRequest;


import net.zjitc.boot_demo.pojo.Admin;
import net.zjitc.boot_demo.service.AdminService;
import net.zjitc.boot_demo.util.APIResponse;
import net.zjitc.boot_demo.util.Token;
import net.zjitc.boot_demo.util.TokenUtil.JwtTokenGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    public String login(Admin admin, Model model, HttpServletRequest request) throws IOException {
        //查询当前用户是否存在
        Admin user = adminService.findAdmin(admin.getUsername(), admin.getPassword());
        if (user!=null){
            request.getSession().setAttribute("admin",user);
            model.addAttribute("msg","登录成功");
            return "success";
        }
        model.addAttribute("msg","登录失败 ");
        return "login";
    }

    @PostMapping("login")
    @ResponseBody
    public APIResponse<Token> login(@RequestBody Admin admin) throws IOException {
        APIResponse<Token> response = new APIResponse<>();
        Admin user = adminService.findAdmin(admin.getUsername(), admin.getPassword());
        response.setData(new Token(""));
        if (user!=null){
            response.setErrno(0);
            response.setErrmsg("登录成功");
            response.setData(new Token(JwtTokenGenerator.generateToken(user.getUsername())));
        }else {
            response.setErrno(1000);
            response.setErrmsg("登录失败");
        }
        System.out.println(response);
        return response;
    }

    @RequestMapping("noToken")
    @ResponseBody
    public APIResponse<String> noToken(){
        APIResponse<String> response = new APIResponse<>();
        response.setErrno(1000);
        response.setErrmsg("token过期或未登录");
        return response;
    }
}

